package com.ylcaifu.common.auto.createApi;



import com.ylcaifu.common.auto.GeneratorBase;
import com.ylcaifu.common.auto.util.CapitalizeUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

/**
 * 自动生成api
 * @author  贤云
 *
 */
public class GeneratorApi extends GeneratorBase {
    public static Connection getConnection(){
        Connection conn = null;
        try {
            Class.forName(GeneratorBase.DRIVER);
            String url = GeneratorBase.URL;
            String user = GeneratorBase.NAME;
            String pass = GeneratorBase.PASS;
            conn = DriverManager.getConnection(url,user,pass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    public static void main(String[] args){
        GeneratorApi generatorInitPageDB=new GeneratorApi();
        generatorInitPageDB.generatorInitPage();
    }
    public  void generatorInitPage(){
        Connection conn=getConnection();
        String sql="select * from "+tablename;
        PreparedStatement stmt;
        String content="";
        String queryParam="";//查询参数
        try {
            stmt = conn.prepareStatement(sql);
            ResultSet rs=stmt.executeQuery(sql);
            ResultSetMetaData data=rs.getMetaData();
            DatabaseMetaData dbmd=conn.getMetaData();
            boolean isNext=true;
            while(rs.next()&&isNext){
                isNext=false;
                for(int i = 1 ; i<= data.getColumnCount() ; i++){
                    //获得所有列的数目及实际列数
                    int columnCount=data.getColumnCount();
                    //获得指定列的列名
                    String columnName = data.getColumnName(i);
                    String columnRemark="";
                    String columnRemarkAll="";
                    ResultSet result = dbmd.getColumns(null, "%", tablename, "%");
                    while(result.next()){
                        if(columnName.contains(result.getString("COLUMN_NAME"))){
                            columnRemark= CapitalizeUtil.initcap(result.getString("REMARKS"));
                            columnRemarkAll=columnRemark;
                            //以分号分隔，可以添加额外的信息
                            columnRemark=columnRemark.split(";")[0];
                        }
                    }
                    //获得指定列的列值
                    String columnValue = rs.getString(i);
                    //获得指定列的数据类型
                    int columnType=data.getColumnType(i);
                    //获得指定列的数据类型名
                    String columnTypeName=data.getColumnTypeName(i);
                    //所在的Catalog名字
                    String catalogName=data.getCatalogName(i);
                    //对应数据类型的类
                    String columnClassName=data.getColumnClassName(i);
                    //在数据库中类型的最大字符个数
                    int columnDisplaySize=data.getColumnDisplaySize(i);
                    //默认的列的标题
                    String columnLabel= CapitalizeUtil.initcap(data.getColumnLabel(i));
                    //获得列的模式
                    String schemaName=data.getSchemaName(i);
                    //某列类型的精确度(类型的长度)
                    int precision= data.getPrecision(i);
                    //小数点后的位数
                    int scale=data.getScale(i);
                    //获取某列对应的表名
                    String tableName=data.getTableName(i);
                    // 是否自动递增
                    boolean isAutoInctement=data.isAutoIncrement(i);
                    //在数据库中是否为货币型
                    boolean isCurrency=data.isCurrency(i);
                    //是否为空
                    int isNullable=data.isNullable(i);
                    //是否为只读
                    boolean isReadOnly=data.isReadOnly(i);
                    //能否出现在where中
                    boolean isSearchable=data.isSearchable(i);
                    //判断是否需要添加查询语句
                    if(i<data.getColumnCount()){
                        queryParam+="" +
                                "\t\t\t\"<div>"+columnLabel+"："+columnRemark+"</div>\"+\n" ;
                    }else{
                        queryParam+="" +
                                "\t\t\t\"<div>"+columnLabel+"："+columnRemark+"</div>\"\n" ;
                    }

                }
            }
            /****************************************自动生成init.jsp页面 start******************************************************************************/

            try {
                content=getInitPageContent(pageTitle, pageOutPath,queryParam,tablename);
                File directory = new File("");
                String newTabelName= CapitalizeUtil.replaceUnderlineAndfirstToUpper(tablename.toLowerCase(),"_","");
                String outputPath = directory.getAbsolutePath()+ "/src/"+this.packageOutPath.replace(".", "/")+"/api/"+initcap(newTabelName) + "Api.java";
                File file=new File(outputPath);
                file.getParentFile().mkdirs();
                FileWriter fw = new FileWriter(outputPath);
                PrintWriter pw = new PrintWriter(fw);
                pw.println(content);
                pw.flush();
                pw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            /****************************************自动生成init.jsp页面 end******************************************************************************/
        } catch (SQLException e) {
            System.out.println("数据库连接失败");
        }
    }

    /**
     *生成初始化页面
     * @param title 页面标题
     * @param path s9/v3/pastInvestmentCase 页面所在路径
     * @return
     */
    public static  String getInitPageContent(String title,String path,String queryParam,String tablename){
        String content="";
        tablename= CapitalizeUtil.replaceUnderlineAndfirstToUpper(tablename.toLowerCase(),"_","");
        content="package "+packageOutPath+".api;\n" +
                "\n" +
                "import com.scienjus.config.ResultStatus;\n" +
                "import com.ylcf.api.bo.*;\n" +
                "import com.ylcf.framework.util.StringUtil;\n" +
                "import org.springframework.stereotype.Controller;\n" +
                "import org.springframework.web.bind.annotation.RequestBody;\n" +
                "import org.springframework.web.bind.annotation.RequestMapping;\n" +
                "import org.springframework.web.bind.annotation.RequestMethod;\n" +
                "import org.springframework.web.bind.annotation.ResponseBody;\n" +
                "import org.springframework.beans.factory.annotation.Autowired;\n" +
                "import org.springframework.beans.factory.annotation.Qualifier;\n"+
                "\n" +
                "import javax.servlet.http.HttpServletRequest;\n" +
                "import javax.servlet.http.HttpServletResponse;\n" +
                "import java.util.HashMap;\n" +
                "import java.util.List;\n" +
                "import java.util.Map;\n" +
                "import "+namespace+"biz.*;\r\n"+
                "import "+namespace+"bo.*;\r\n"+
                "import "+namespace+"entity.*;\r\n"+
                "\n" +
                "/**\n" +
                " *用户自动生成api controller样例\n" +
                " * @author zhengyunfei\n" +
                " */\n" +
                "\n" +
                "@Controller\n" +
                "public class "+initcap(tablename)+"Api {\n" +
                "\t/**\n" +
                "\t * demo列表-app\n" +
                "\t */\n" +
                "\t@RequestMapping(value = \""+path+"\", method = RequestMethod.POST)\n" +
                "\t@ResponseBody\n" +
                "\tpublic Object add(@RequestBody PageBo bo, HttpServletRequest request, HttpServletResponse response) {\n" +
                "\t\tReturnInfo returnInfo=new ReturnInfo();\n" +
                "\t\ttry{\n" +
                "\t\t\tMap<String, List<?>> data=new HashMap<String,List<?>>();\n" +
                "\t\t\t/*********************************查询"+title+"列表start 每页显示10条*******************************************************/\n" +
                "\t\t\tList<"+initcap(tablename)+"Bo> list = null;\n" +
                "\t\t\t"+initcap(tablename)+"Bo boParam=new  "+initcap(tablename)+"Bo();\n" +
                "\t\t\tboParam.setCurNo((bo.getPageNow()-1)*bo.getPageSize());\n" +
                "\t\t\tboParam.setCurSize(bo.getPageSize());\n" +
                "\t\t\tlist = "+tablename+".findAllList(boParam);\n" +
                "\t\t\tif(!StringUtil.isNullOrEmpty(list)&&list.size()>0){\n" +
                "\t\t\t\treturnInfo.setCode(ResultStatus.SUCCESS.getCode());\n" +
                "\t\t\t\treturnInfo.setMessage(ResultStatus.SUCCESS.getMessage());\n" +
                "\t\t\t}else{\n" +
                "\t\t\t\treturnInfo.setCode(ResultStatus.NO_MORE.getCode());\n" +
                "\t\t\t\treturnInfo.setMessage(ResultStatus.NO_MORE.getMessage());\n" +
                "\t\t\t}\n" +
                "\t\t\tdata.put(ReturnDataTypeCommon.LIST,list);\n" +
                "\t\t\t/*********************************查询"+title+"列表end*******************************************************/\n" +
                "\t\t\treturnInfo.setData(data);\n" +
                "\t\t}catch (Exception e){\n" +
                "\t\t\te.printStackTrace();\n" +
                "\t\t}\n" +
                "\t\treturn returnInfo;\n" +
                "\t}\n" +
                "\n" +
                "\t/*\n" +
                "\t * 基金服务层接口注入\n" +
                "\t */\n" ;

                content+="\t@Autowired @Qualifier(\""+tablename+"\")\r\n";
                content+="\tprivate I"+initcap(tablename)+" "+tablename+";\r\n";
                content+="\n" +
                "}\n";
        return content;
    }

    /**
     * 功能：将输入字符串的首字母改成大写
     * @param str
     * @return
     */
    private static String initcap(String str) {

        char[] ch = str.toCharArray();
        if(ch[0] >= 'a' && ch[0] <= 'z'){
            ch[0] = (char)(ch[0] - 32);
        }

        return new String(ch);
    }
}
